package com.qqtop10.manager.controller;

import com.alibaba.druid.util.StringUtils;
import com.qqtop10.manager.model.PagingArgs;
import com.qqtop10.manager.model.Result;
import com.qqtop10.manager.model.Shop;
import com.qqtop10.manager.service.OssImgService;
import com.qqtop10.manager.service.ShopService;
import com.qqtop10.manager.utils.oss.OSSFilePath;
import com.qqtop10.manager.utils.oss.OSSUploadUtils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping({ "/manager/shop/" })
@Controller
public class ShopController extends BaseController {
	@Autowired
	@Qualifier("shopService")
	private ShopService shopService;

	@Autowired
	@Qualifier("ossImgService")
	private OssImgService ossImgService;

	@RequestMapping({ "all.do" })
	@ResponseBody
	public Result all(HttpServletRequest request, HttpServletResponse response, Shop input) {
//		String where = request.getParameter("where");
		String status = request.getParameter("status");
		StringBuffer sb = new StringBuffer();
		try {
			sb.append(" shop_type in (1,2,3,4,5) ");
//			String[] array = where.split(",");
//			if (array.length > 0) {
//				if (Integer.parseInt(array[0]) > 0) {
//					for (int i = 0; i < array.length; i++) {
//						sb.append("shop_type = " + array[i]);
//						if (i < array.length - 1) {
//							sb.append(" and ");
//						}
//					}
//				} else if (Integer.parseInt(array[0]) < 0) {
//					for (int i = 0; i < array.length; i++) {
//						sb.append("shop_type != " + Math.abs(Integer.parseInt(array[i])));
//						if (i < array.length - 1) {
//							sb.append(" and ");
//						}
//					}
//				}
//			}
			if ((status == null) || (status.equals(""))) {
				input.setStatus(Integer.valueOf(1));
			}
			PagingArgs pagingArgs = getPagingArgs();
			input.setPromise(sb.toString());
			// System.out.println(this.shopService.all(input,
			// pagingArgs).get(0).getIsBZJ());
			Result page = page(this.shopService.count2(input), this.shopService.all(input, pagingArgs));
			return page;
		} catch (Exception e) {
			return excep(e);
		}
	}

	@RequestMapping({ "approve.do" })
	@ResponseBody
	public Result approve(Shop input, HttpServletRequest request, HttpServletResponse response) {
		if ((input == null) || (input.getId() == null) || (input.getStatus() == null)) {
			return new Result(1, "有些必须的参数未指定。");
		}
		try {
			input.setMender(getLogindUuid());
			input.setUpdatetime(now());
			if (this.shopService.approve(input)) {
				// 审核成功时，创建小能客服商户ID
				this.shopService.applyXNShopId(input);
				return ok("操作成功!");
			}
			return err("操作失败!");
		} catch (Exception e) {
			return excep(e);
		}
	}

	@RequestMapping(value = "update.do", method = RequestMethod.POST)
	// @RequestMapping({ "update.do" })
	@ResponseBody
	public Result update(Shop input, HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {

		String c = request.getParameter("city");

		String s = URLDecoder.decode(c, "UTF-8");

		/*
		 * input.setCity(URLDecoder.decode(input.getCity(),"UTF-8"));
		 * input.setProvince(URLDecoder.decode(input.getProvince(),"UTF-8"));
		 * input.setDistrict(URLDecoder.decode(input.getDistrict(),"UTF-8"));
		 * input.setName(URLDecoder.decode(input.getName(),"UTF-8"));
		 * input.setStreet(URLDecoder.decode(input.getStreet(),"UTF-8"));
		 */
		/*
		 * MultipartFile logo = getFile("logo"); MultipartFile businessLicence =
		 * getFile("business_licence");
		 * 
		 * MultipartFile positive_identity_card = getFile("idcard");
		 * MultipartFile The_opposite_of_ID_card = getFile("idcard2");
		 * MultipartFile Tax_registration_certificate = getFile("tax_permit");
		 * MultipartFile Organization_code_certificate =
		 * getFile("organization_permit"); MultipartFile
		 * Open_bank_account_permit_certificate = getFile("bank_permit");
		 * 
		 * if ((positive_identity_card != null) &&
		 * (!positive_identity_card.isEmpty())) {
		 * input.setIdcard(save(positive_identity_card)); } if
		 * ((The_opposite_of_ID_card != null) &&
		 * (!The_opposite_of_ID_card.isEmpty())) {
		 * input.setIdcard2(save(The_opposite_of_ID_card)); } if
		 * ((Tax_registration_certificate != null) &&
		 * (!Tax_registration_certificate.isEmpty())) {
		 * input.setTax_permit(save(Tax_registration_certificate)); } if
		 * ((Organization_code_certificate != null) &&
		 * (!Organization_code_certificate.isEmpty())) {
		 * input.setOrganization_permit(save(Organization_code_certificate)); }
		 * if ((Open_bank_account_permit_certificate != null) &&
		 * (!Open_bank_account_permit_certificate.isEmpty())) {
		 * input.setBank_permit(save(Open_bank_account_permit_certificate)); }
		 * 
		 * if ((logo != null) && (!logo.isEmpty())) { input.setLogo(save(logo));
		 * }
		 * 
		 * if ((businessLicence != null) && (!businessLicence.isEmpty())) {
		 * input.setBusiness_licence(save(businessLicence)); }
		 */
		if ((input == null) || (input.getCellphone() == null) || (input.getCity() == null)
				|| (input.getContacts() == null) || (input.getDetailed_address() == null)
				|| (input.getDistrict() == null) || (input.getEmail() == null) || (input.getIdcard_number() == null)
				|| (isNull(input.getLogo())) || (input.getName() == null) || (input.getProvince() == null)
				|| (input.getTelephone() == null) || (isNull(input.getBusiness_licence()))) {
			return err("有些必须的参数未指定。");
		}
		try {
			// String c=request.getParameter(name);

			input.setUpdatetime(now());
			input.setMender(getLogindUuid());
			if (this.shopService.updateBySelective(input) > 0) {
				shopService.applyXNShopId(input);
				return ok("操作成功!", input);
			}
			return err("操作失败!");
		} catch (Exception e) {
			return excep(e);
		}
	}

	@RequestMapping({ "setStatus.do" })
	@ResponseBody
	public Result setStatus(HttpServletRequest request, HttpServletResponse response) {
		Result result = new Result(1);
		String status = request.getParameter("status");
		int id = 0;
		try {
			id = Integer.parseInt(request.getParameter("id"));
			if ((status == null) || ("".equals(status))) {
				result.setCode(99);
				result.setMsg("状态不能为空");
			} else {
				Shop shop = new Shop();
				shop.setId(Integer.valueOf(id));
				if (status.equals("1")) {
					shop.setStatus(Integer.valueOf(1));
					int i = this.shopService.updateBySelective(shop);
					if (i > 0) {
						result.setMsg("商店启用成功");
					} else {
						result.setCode(99);
						result.setMsg("商店启用失败");
					}
				} else if (status.equals("2")) {
					shop.setStatus(Integer.valueOf(2));
					int i = this.shopService.updateBySelective(shop);
					if (i > 0) {
						result.setMsg("商店禁用成功");
					} else {
						result.setCode(99);
						result.setMsg("商店禁用失败");
					}
				} else {
					result.setCode(99);
					result.setMsg("参数不正确");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("更改商店状态失败：" + e.getMessage());
		}
		return result;
	}

	@RequestMapping("uploadFile.do")
	@ResponseBody
	public Result uploadFile(HttpServletRequest request) {
		Result result = new Result();
		String shopId = request.getParameter("shopId");
		if (StringUtils.isEmpty(shopId)) {
			result.setCode(99);
			result.setMsg("操作的商户ID为空");
			return result;
		}
		final MultipartFile file = getFile("file");
		Shop shop = new Shop();
		shop.setId(Integer.parseInt(shopId));
		shop = shopService.get(shop);
		String fileId = newId();
		String oldName = file.getOriginalFilename();
		oldName = oldName != null && oldName.length() != 0 && oldName.lastIndexOf('.') != -1
				? oldName.substring(oldName.lastIndexOf('.')) : "";
		// 创建OSS上传对象
		String url = OSSFilePath.USUALLYSAVEPATHPREFIX + fileId + oldName;
//		new Thread(new Runnable(){
//			public void run(){
				OSSUploadUtils ossUploadUtils = new OSSUploadUtils();
				// OSS上传图片操作
				ossUploadUtils.uploadFile(url, file);
				// 关闭OSS客户端
				ossUploadUtils.closeOssClient();
//			}
//		}).start();
		
		String fullFileName = OSSFilePath.OSSDOMAIN + "/images/files/" + fileId + oldName;
		result.setCode(0);
		result.setData(fullFileName);
		return result;
	}
}
